package xq.gwt.ui.widgets.entity;


import xq.gwt.mvc.model.EntityModel;
import xq.gwt.ui.widgets.command.CommandListPresenter;
import xq.gwt.ui.widgets.command.VerticalButtonsCommandListPresenter;
import xq.gwt.ui.widgets.property.PropertyListPresenter;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.layout.HLayout;



public class HorisontalFormEntityPresenter implements EntityPresenter{
	protected DynamicForm form;
	protected EntityModel entity;
	protected PropertyListPresenter propPresenter;
	protected HLayout mainLayout = new HLayout();
	protected HLayout buttonLayout = new HLayout();
	protected CommandListPresenter commandPresenter;
	protected CommandPosition commandPosition = CommandPosition.Top;
	
	public HorisontalFormEntityPresenter(){
		form = new DynamicForm();
		commandPresenter = new VerticalButtonsCommandListPresenter();
		init();
	}
	
	public HorisontalFormEntityPresenter(DynamicForm form){
		this.form = form;
		commandPresenter = new VerticalButtonsCommandListPresenter();
		init();
	}
	
	public HorisontalFormEntityPresenter(CommandListPresenter commandListPresenter){
		form = new DynamicForm();
		this.commandPresenter = commandListPresenter;
		init();
	}
	
	public HorisontalFormEntityPresenter(DynamicForm form, CommandListPresenter commandListPresenter){
		this.form = form;
		this.commandPresenter = commandListPresenter;
		init();
	}
	
	protected void init(){		
		propPresenter = new PropertyListPresenter(form);		
		this.form.setWidth("100%");
		this.form.setAlign(Alignment.LEFT);
		this.commandPresenter.getCanvas().setAlign(Alignment.LEFT);
		mainLayout.setMembersMargin(6);
	}
	
	public void setEntity(EntityModel entity){		
		this.entity = entity;
		form.setTitle(entity.getTitle());
		if(form.getIsGroup())
			form.setGroupTitle(entity.getTitle());
		//show fields				
		propPresenter.setProperties(this.entity.getProperties());		
		
		//show commands			
		if(this.entity != null){
			commandPresenter.setCommands(this.entity.getCommands());
			buttonLayout.setMembers(commandPresenter.getCanvas());
		}					
	}

	public Canvas getCanvas() {		
		
		switch (commandPosition) {
		case Top:
			if(!mainLayout.contains(buttonLayout))
				mainLayout.addMember(buttonLayout);
			if(!mainLayout.contains(form))
				mainLayout.addMember(form);			
			break;
		case Bottom:			
			if(!mainLayout.contains(form))
				mainLayout.addMember(form);
			if(!mainLayout.contains(buttonLayout))
				mainLayout.addMember(buttonLayout);			
			break;
		default:
			break;
		}
		
				
		return mainLayout;
	}
	
	
	
	public CommandPosition getCommandPosition() {
		return commandPosition;
	}

	public void setCommandPosition(CommandPosition commandPosition) {
		this.commandPosition = commandPosition;
	}

	public enum CommandPosition {
		Top, Bottom;
	}
}
